<?php

if($argc<=1){
	echo $argv[0].": ".$argv[0]." [fullpathname of configuration file]";
	exit();
}

$configfile = $argv[1];
if(!is_file($configfile)){
	echo $argv[0].": Configuration file ".$configfile." not found";
	exit();	
}

$configlines = explode("\n",file_get_contents($configfile));
$_CONFIG = array();
foreach($configlines as $k=>$d){
	$pair = preg_split("/=/",$d);
	if(count($pair)>1){
		$data = trim($pair[1]);
		$key = trim($pair[0]);
		$_CONFIG[$key]=$data;
	}
}

set_time_limit (0);
$address = '0.0.0.0';
$port = 9000;
$flagfile = "reboot.flg";
if(isset($_CONFIG['address']))$address = $_CONFIG['address'];
if(isset($_CONFIG['port']))$port = $_CONFIG['port']; 
if(isset($_CONFIG['flagfile']))$flagfile = $_CONFIG['flagfile']; 
while(true){
	$sock = socket_create(AF_INET, SOCK_STREAM, 0);
	socket_bind($sock, $address, $port) or die('Could not bind to address');
	socket_listen($sock);
	$client = socket_accept($sock);
	while(true){
		$_GET = array();
		$requestfile = "";
		$input = @socket_read($client, 1024);
		//echo $input;
		$requestlines = explode("\r\n",$input);
		foreach($requestlines as $k=>$d){
			if(substr($d,0,3)=="GET"){
				//echo $d;
				$parts = preg_split("/\s/",$d);
				$request = $parts[1];
				// Get any request arguments
				$requestparts = preg_split("/\?/",$request);
				$requestfile = $requestparts[0];
				if(isset($requestparts[1])){
					// Yep. Got arguments
					$argpairs = preg_split("/&/",$requestparts[1]);
					//print_r($argpairs);
					foreach($argpairs as $k=>$d){
						$pairs = preg_split("/=/",$d);
						$data = "";
						if(isset($pairs[1]))$data=$pairs[1];
						$arg = $pairs[0];
						$_GET[$arg]=$data;
					}
				}
			}
		}
		$html = "<b>Bad Request!</b>";
		if($requestfile=="/reimage"){
			if(isset($_GET['user']) && isset($_GET['pass']) && isset($_CONFIG['user']) && isset($_CONFIG['pass'])){
				if($_GET['user']==$_CONFIG['user'] && $_GET['pass']==$_CONFIG['pass']){
					fopen($flagfile,"w+");
					$html = "<b>Reimage Requested</b>";
				}
			}
		}
			
		
		$response = "HTTP/1.1 200 OK\r\n";
		$response .= "Date: ".date("r")."\r\n";
		$response .= "Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)\r\n";
		$response .= "Last-Modified: ".date("r")."\r\n";
		$response .= "Etag: \"".md5(time())."\"\r\n";
		$response .= "Content-Type: text/html; charset=UTF-8\r\n";
		$response .= "Content-Length: ".strlen($html)."\r\n";
		$response .= "Connection: close\r\n\r\n";
		$response .= $html;
		$output = $response.chr(0);
		$sent = @socket_write($client, $output);
		if($sent===false)
			break;
		
	}
	socket_close($client);
	socket_close($sock);
}

?>